package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.WipCompletionExport;
import com.pureut.storage.mapper.PublicGoodsMapper;
import com.pureut.storage.mapper.WipCompletionDetailMapper;
import com.pureut.storage.mapper.WipCompletionMapper;
import com.pureut.storage.mapper.WmsStockInfoMapper;
import com.pureut.storage.service.WarehouseService;
import com.pureut.storage.service.WipCompletionDetailService;
import com.pureut.storage.service.WipCompletionService;
import com.pureut.storage.service.WmsStockInfoService;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.UpdateStatusByQualityVo;
import com.pureut.storage.vo.WipCompletionVo;
import com.pureut.storage.vo.WipOtherAddVo;
import com.pureut.storage.vo.WipVo;
import com.pureut.storage.vo.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.QualityFeginService;
import com.pureut.system.api.SystemDocumentFeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/***
 *
 * Author:C
 * Date:2022/12/30 11:55
 * @DESC
 */
@Service
public class WipCompletionServiceImpl extends ServiceImpl<WipCompletionMapper, WipCompletion> implements WipCompletionService {

    @Resource
    WipCompletionMapper wipCompletionMapper;

    @Resource
    WarehouseService warehouseService;

    @Resource
    FeignService feignService;

    @Resource
    WipCompletionDetailMapper wipCompletionDetailMapper;

    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    @Resource
    WmsStockInfoService wmsStockInfoService;

    @Resource
    WipCompletionDetailService wipCompletionDetailService;

    @Resource
    SystemDocumentFeignService systemDocumentFeignService;

    @Resource
    FeignProductionService feignProductionService;

    @Resource
    QualityFeginService qualityFeginService;


    /**
     * 完工入库列表
     *
     * @param wipCompletionVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<WipCompletionDto> getReceiptList(WipCompletionVo wipCompletionVo) {
        List<WipCompletionDto> wipCompletionList = wipCompletionMapper.getWipCompletionList(wipCompletionVo);
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取完工入库状态字典值
        List<SysDictData> receiptArray = DictUtils.getDictCache("wip_completion_status");
        Map<String, String> wipStatusMap = receiptArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取完工入库收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("wip_completion_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (WipCompletionDto entity : wipCompletionList) {
            //状态
            entity.setStatusDict(wipStatusMap.get(entity.getStatus()));
            //仓库
            entity.setWarehousingWarehouse(entity.getWarehousingWarehouse());
            entity.setWarehouseName(entity.getWarehouseName());
            //单据类型
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(entity.getDocumentType()));
            //收发类型
            entity.setReceiveTypeDict(rdMap.get(entity.getReceiveType()));
            //生成方式
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(entity.getGenerationMethod()));
            //物料类型
            entity.setMaterialName(entity.getMaterialName());
            entity.setMaterialCode(entity.getMaterialCode());
            entity.setMaterialSpec(entity.getMaterialSpec());
            //单位
            entity.setMaterialUnitDict(unitMap.get(entity.getMaterialUnit()));

        }
        return wipCompletionList;
    }

    /**
     * 新增
     *
     * @param wipCompletionVo
     * @return
     */
    @Override
    public boolean addWipCompletion(WipCompletionVo wipCompletionVo) throws Exception {

        List<WipVo> wipList = wipCompletionVo.getWipList();
        List<WipCompletion> wipCompletionList = new ArrayList<>();
        if (wipList.size() > 0) {
            for (WipVo entity : wipList) {
                WipCompletion wipCompletion = new WipCompletion();
                String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:finished:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                wipCompletion.setReceiptNo(feignService.splitList("WGRK"))
                        .setDeptId(SecurityUtils.getDeptId())
                        .setStatus(1)
                        .setMakingOrderNo(entity.getMakingOrderNo())
                        .setMaterialId(entity.getMaterialId())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialCategory(entity.getMaterialCategory())
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                        .setWarehousTime(wipCompletionVo.getWarehousTime())
                        .setRemark(wipCompletionVo.getRemark())
                        .setDrawerBy(SecurityUtils.getUsername())
                        .setDrawerTime(new Date())
                        .setReceiveType(wipCompletionVo.getReceiveType())
                        .setDocumentType(DocumentTypeEnum.WIP_COMPLETION.getCode());

                if (wipCompletionVo.getGenerationMethod() != 2) {
                    wipCompletion.setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
                } else {
                    wipCompletion.setGenerationMethod(GenerationMethodEnum.AUTO_GENERATE.getCode());
                }
                wipCompletionList.add(wipCompletion);
            }
            return saveBatch(wipCompletionList);
        } else {
            throw new GlobalException("请至少选择一条数据");
        }
    }

    /**
     * 关结
     *
     * @param wipCompletionVo
     * @return
     */
    @Override
    public boolean close(WipCompletionVo wipCompletionVo) {
        WipCompletion wipCompletion = getById(wipCompletionVo.getId());
        //已完成、已关结不可重复关结；
        if (wipCompletion.getStatus() != 4 || wipCompletion.getStatus() != 5) {

            wipCompletion.setStatus(5)
                    .setCloseReason(wipCompletionVo.getCloseReason())
                    .setClosingBy(SecurityUtils.getUsername())
                    .setClosingTime(new Date());

            //待检验状态的单据关结后，单据状态更新为“已关结”，跳过后续操作，入库的物料显示为在库，关联的品质检验单状态更新为“已撤销”；
            if (wipCompletion.getStatus() == 3) {
                List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = wipCompletionDetails.stream()
                        .filter(entity -> entity.getStatus() == 2)
                        .map(WipCompletionDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if(!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
                //修改对应品质检验单状态为已撤销
                UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                updateQualityStatusVo.setAssociatedNo(wipCompletion.getReceiptNo());
                updateQualityStatusVo.setStatus(8);
                qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);

            }
            //待入库状态的单据关结后，单据状态更新为“已关结”，无影响；
//            if (wipCompletion.getStatus() == 1) {
//
//            }
            //入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库（完工入库未扫描到的条码在库存中没有库区库位）
            if (wipCompletion.getStatus() == 2) {
                List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = wipCompletionDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 3)
                        .map(WipCompletionDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if(!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
            }
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }
        return updateById(wipCompletion);

    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public WipCompletionDto getView(Long id) {

        WipCompletionDto wipCompletionById = wipCompletionMapper.getWipCompletionById(id);

        //获取完工入库收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("wip_completion_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //单据类型
        wipCompletionById.setDocumentTypeDict(DocumentTypeEnum.getValue(wipCompletionById.getDocumentType()));

        //收发类型
        wipCompletionById.setReceiveTypeDict(rdMap.get(String.valueOf(wipCompletionById.getReceiveType())));

        //生成方式
        wipCompletionById.setGenerationMethodDict(GenerationMethodEnum.getValue(wipCompletionById.getGenerationMethod()));

        List<WipVo> wipVoList = new ArrayList<>();
        WipVo wipVo = new WipVo();
        wipVo.setMakingOrderNo(wipCompletionById.getMakingOrderNo());
        wipVo.setPlannedWeight(wipCompletionById.getPlannedWeight());
        //仓库
        wipVo.setWarehousingWarehouse(Long.parseLong(wipCompletionById.getWarehousingWarehouse()));
        wipVo.setWarehousingWarehouseDict(wipCompletionById.getWarehouseName());
        //物料信息
        wipVo.setMaterialName(wipCompletionById.getMaterialName());
        wipVo.setMaterialCode(wipCompletionById.getMaterialCode());
        wipVo.setMaterialSpec(wipCompletionById.getMaterialSpec());
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        wipVo.setMaterialUnit(wipCompletionById.getMaterialUnit());
        wipVo.setMaterialUnitDict(unitMap.get(wipCompletionById.getMaterialUnit()));
        wipVoList.add(wipVo);
        wipCompletionById.setWipList(wipVoList);
        return wipCompletionById;
    }


    /**
     * 修改
     *
     * @param wipCompletionVo
     * @return
     */
    @Override
    public boolean updateWipCompletion(WipCompletionVo wipCompletionVo) {

        WipCompletion wipCompletion = getById(wipCompletionVo.getId());
        if (wipCompletion.getStatus() == 1) {
            wipCompletion.setReceiveType(wipCompletionVo.getReceiveType());
            wipCompletion.setWarehousTime(wipCompletionVo.getWarehousTime());
            wipCompletion.setRemark(wipCompletionVo.getRemark());
            List<WipVo> wipList = wipCompletionVo.getWipList();
            for (WipVo entity : wipList) {
                wipCompletion.setMakingOrderNo(entity.getMakingOrderNo())
                        .setPlannedWeight(entity.getPlannedWeight())
                        .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                        .setMaterialCode(entity.getMaterialCode())
                        .setMaterialId(entity.getMaterialId());
            }
            return updateById(wipCompletion);
        } else {
            throw new GlobalException("只能修改待入库的数据");
        }
    }


    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteWipCompletion(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("请至少选择一条数据");
        }
        List<WipCompletion> wipCompletionList = new ArrayList<>();
        List<WipCompletion> wipCompletions = wipCompletionMapper.selectList(new QueryWrapper<WipCompletion>().lambda().in(WipCompletion::getId, idList));
        for (WipCompletion entity : wipCompletions) {
            if (entity.getStatus() == 1) {
                wipCompletionList.add(entity);
            } else {
                throw new GlobalException("只能删除待入库的单据");
            }
        }
        List<WipCompletion> deleteList = new ArrayList<>();
        for (WipCompletion entity : wipCompletionList) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        return removeByIds(deleteList);
    }


    /**
     * 导出
     *
     * @param wipCompletionVo
     * @return
     */
    @Override
    public List<WipCompletionExport> getInfoExport(WipCompletionVo wipCompletionVo) {
        List<WipCompletionExportDto> wipCompletionList;


        if (wipCompletionVo.getIdStr() == null) {
            wipCompletionList = wipCompletionMapper.getWipCompletionListOut(wipCompletionVo);
        } else {
            List<String> idList = Arrays.asList(wipCompletionVo.getIdStr().split(","));
            wipCompletionList = wipCompletionMapper.getDataByIdStr(idList);
        }

        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //获取完工入库收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("wip_completion_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<WipCompletionExport> wipCompletionExportList = new ArrayList<>();
        for (WipCompletionExportDto entity : wipCompletionList) {
            WipCompletionExport wipCompletionExport = new WipCompletionExport();


            BeanUtils.copyProperties(entity, wipCompletionExport);
            //收发类型
            if (!"0".equals(entity.getReceiveType())) {
                wipCompletionExport.setReceiveType(rdMap.get(String.valueOf(entity.getReceiveType())));
            } else {
                wipCompletionExport.setReceiveType("");
            }
            wipCompletionExport.setMaterialNetDict(netMap.get(entity.getMaterialNetDict()));
            wipCompletionExport.setMaterialNetTypeDict(netTypeMap.get(entity.getMaterialNetTypeDict()));
            wipCompletionExportList.add(wipCompletionExport);
        }
        return wipCompletionExportList;
    }

    /**
     * 完工入库pda（自动生成）
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto wipCompletionPda(PickingRestDbVo pickingRestDbVo) throws Exception {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        WipCompletion wipCompletion = getById(pickingRestDbVo.getId());
        //判断该数据的生成方式
        if (wipCompletion.getGenerationMethod() == 1) {
            if (wipCompletion.getStatus() == 1 || wipCompletion.getStatus() == 2) {
                //扫码入库
                if ("1".equals(pickingRestDbVo.getType())) {
                    //如果是第一步，需要查询库位信息
                    if (pickingRestDbVo.getExecutionOrder() == 1) {
                        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                        if (warehouseCode.getCombinationName() == null) {
                            pickingRestDbDto.setMessage("该仓库不存在，请核实");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }
                        pickingRestDbDto.setCombinationName(warehouseCode.getCombinationName());
                        pickingRestDbDto.setCkId(warehouseCode.getCkId());
                        pickingRestDbDto.setKqId(warehouseCode.getKqId());
                        pickingRestDbDto.setKwId(warehouseCode.getKwId());
                        pickingRestDbDto.setMessage("操作成功");
                        pickingRestDbDto.setCode("200");
                        return pickingRestDbDto;
                    }
                    //如果是第二步，需要根据物料号码查询明细信息
                    if (pickingRestDbVo.getExecutionOrder() == 2) {
                        WipCompletionDetail wipCompletionDetail = wipCompletionDetailMapper.selectOne(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                        //获取仓库数据
                        WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wipCompletionDetail.getMaterialNumber()));
                        //判断该明细是否已经入库过
                        if (wipCompletionDetail.getStatus() == 2) {
                            pickingRestDbDto.setMessage("该数据已经入库");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }
                        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletionDetail.getMaterialCode()));

                        Long menuId = feignService.getIdByMenuName("完工入库");
                        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

                        //如果配置了送检,则校验是否配了检验方案
                        if (sysDocument.getDocInspectionMark()==1){

                            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                            if (documentCheckDtoList==null){
                                throw new GlobalException("请先在单据配置中配置送检方案");
                            }


                            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualitySchemeConfigurationVo.setMaterialCode(wipCompletion.getMaterialCode());
                            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                            if (!check){
                                throw new GlobalException("该物料不存在对应的检验方案");

                            }
                        }

                        //判断是否配置了送检
                        if (sysDocument.getDocInspectionMark() == 1) {
                            //修改明细状态为待送检
                            wipCompletionDetail.setStatus(2);
                            wipCompletionDetail.setWarehouseInBy(SecurityUtils.getUsername());
                            wipCompletionDetail.setWarehouseInTime(new Date());
                            wipCompletionDetailService.updateById(wipCompletionDetail);
                            //同时修改仓库表中对应的数据状态为在库
                            wmsStockInfo.setWsiMaterialStatus(2);
                            wmsStockInfo.setWsiMaterialType(publicGoods.getMaterialType());
                            wmsStockInfo.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                            wmsStockInfo.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                            wmsStockInfo.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                            wmsStockInfo.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                            wmsStockInfo.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                            wmsStockInfo.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                            wmsStockInfo.setWsiDocNum(wipCompletion.getReceiptNo());
                            wmsStockInfo.setWsiMaterialGrade("1");
                            wmsStockInfo.setCreateUser(SecurityUtils.getUsername());
                            wmsStockInfo.setCreateTime(new Date());
                            wmsStockInfo.setWsiReveiveTime(new Date());
                            wmsStockInfoService.updateById(wmsStockInfo);
                        } else {
                            //否则就修改为已经完成
                            wipCompletionDetail.setStatus(3);
                            wipCompletionDetail.setWarehouseInBy(SecurityUtils.getUsername());
                            wipCompletionDetail.setWarehouseInTime(new Date());
                            wipCompletionDetailService.updateById(wipCompletionDetail);
                            //同时修改仓库表中对应的数据状态为在库
                            wmsStockInfo.setWsiMaterialStatus(2);
                            wmsStockInfo.setWsiMaterialType(publicGoods.getMaterialType());
                            wmsStockInfo.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                            wmsStockInfo.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                            wmsStockInfo.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                            wmsStockInfo.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                            wmsStockInfo.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                            wmsStockInfo.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                            wmsStockInfo.setWsiDocNum(wipCompletion.getReceiptNo());
                            wmsStockInfo.setWsiMaterialGrade("1");
                            wmsStockInfo.setCreateUser(SecurityUtils.getUsername());
                            wmsStockInfo.setCreateTime(new Date());
                            wmsStockInfo.setWsiReveiveTime(new Date());
                            wmsStockInfoService.updateById(wmsStockInfo);
                        }

                        //获取单位字典值
                        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                        //判断单位
                        if ("2".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是千克
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                wipCompletion.setActualQuantity(String.valueOf(wipCompletionDetail.getNetWeight()));
                                //修改采购入库信息入库重量
                                wipCompletion.setWarehousingWeight(wipCompletionDetail.getNetWeight());
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s = bigDecimal.add(bigDecimal1).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                            }
                        } else if ("3".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                BigDecimal bigDecimal = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                                wipCompletion.setActualQuantity(divide.toString());
                                //修改采购入库信息入库重量
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                                String s = bigDecimal.add(divide).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                            }
                        } else {
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                wipCompletion.setActualQuantity(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                //修改采购入库信息入库重量
                                wipCompletion.setWarehousingWeight(wipCompletionDetail.getNetWeight());
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                String s = bigDecimal.add(bigDecimal1).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                            }
                        }
                        int warehousingNum = wipCompletion.getWarehousingNum();
                        if (warehousingNum == 0) {
                            wipCompletion.setWarehousingNum(1);
                        } else {
                            wipCompletion.setWarehousingNum(warehousingNum + 1);
                        }

                        pickingRestDbDto.setQuantityIdentification(wipCompletion.getPlannedWeight() + "/" + wipCompletion.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setMessage("物料号码:" + wipCompletionDetail.getMaterialNumber() + "," + "净重:" + wipCompletionDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + wipCompletionDetail.getReceiptQuantity() + "," + "录入成功");
                        pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                        pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setWarehouseNumber(String.valueOf(wipCompletion.getWarehousingNum()));

                        //需求量
                        double aDouble = Double.parseDouble(wipCompletion.getActualQuantity());
                        //计划量
                        double plannedWeight = wipCompletion.getPlannedWeight();
                        boolean b = Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(plannedWeight);
                        if (b) {
                            //如果配置了送检
                            if (sysDocument.getDocInspectionMark() == 1) {
                                wipCompletion.setStatus(3);

                                // 生成品质检验单
                                if (sysDocument.getDocCode() == null) {
                                    throw new GlobalException("未进行单据配置");
                                }
                                List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                                if (documentCheckDtoList.size() < 1) {
                                    throw new GlobalException("未进行检验单生成配置");
                                }
                                //通过物料编码获取物料类别
                                //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
                                //获取明细列表
                                List<WipCompletionDetail> salesReturnDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                                StringBuilder stringBuilder = new StringBuilder();
                                for (WipCompletionDetail entity : salesReturnDetailList) {
                                    stringBuilder.append(entity.getBatchNo()).append(",");
                                }
                                StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                                for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                                    if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                                        QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                                        qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                                        qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                                        qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                                        qualityInspectionDocumentVo.setMaterialCode(wipCompletion.getMaterialCode());
                                        qualityInspectionDocumentVo.setBatchNo(stringBuilder1.toString());
                                        qualityInspectionDocumentVo.setAssociatedNo(wipCompletion.getReceiptNo());
                                        qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                        qualityInspectionDocumentVo.setModeType(15);

                                        List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                                        for (WipCompletionDetail entity : salesReturnDetailList) {
                                            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                            materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                                            materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                                            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                        }
                                        qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                                        boolean b1 = qualityFeginService.addWares(qualityInspectionDocumentVo);
                                        if (!b1) {
                                            throw new GlobalException("未进行单据配置，请前往品质检验——>检验项目进行配置");
                                        }
                                    }
                                }
                                updateById(wipCompletion);
                                wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            } else {
                                //如果没有配置送检且单据对应的明细都已经入库，那么就修改为已完成
                                boolean a = true;
                                List<WipCompletionDetail> wipCompletionDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                                for (WipCompletionDetail entity : wipCompletionDetailList) {
                                    if (entity.getStatus() != 3) {
                                        wipCompletion.setStatus(2);
                                        a = false;
                                        break;
                                    }
                                }
                                if (a) {
                                    wipCompletion.setStatus(4);
                                }
                                wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                updateById(wipCompletion);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                        }
                        wipCompletion.setStatus(2);
                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                        updateById(wipCompletion);
                        pickingRestDbDto.setCode("200");
                        return pickingRestDbDto;
                    }
                }
                //批次入库
                if ("2".equals(pickingRestDbVo.getType())) {
                    //如果是第一步，需要查询库位信息
                    if (pickingRestDbVo.getExecutionOrder() == 1) {
                        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                        pickingRestDbDto.setCombinationName(warehouseCode.getCombinationName());
                        if (warehouseCode.getCombinationName() == null) {
                            pickingRestDbDto.setMessage("该仓库不存在，请核实");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }
                        pickingRestDbDto.setCkId(warehouseCode.getCkId());
                        pickingRestDbDto.setKqId(warehouseCode.getKqId());
                        pickingRestDbDto.setKwId(warehouseCode.getKwId());
                        pickingRestDbDto.setMessage("操作成功");
                        pickingRestDbDto.setCode("200");
                        return pickingRestDbDto;
                    }
                    //如果是第二步，需要根据批次号查询明细信息
                    if (pickingRestDbVo.getExecutionOrder() == 2) {
                        List<WipCompletionDetail> wipCompletionDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getBatchNo, pickingRestDbVo.getInputValue()).eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                        //判断该批次中是否有已经入库的数据
                        boolean isNoWarehousing = true;
                        for (WipCompletionDetail entity : wipCompletionDetailList) {
                            if (entity.getStatus() == 2) {
                                isNoWarehousing = false;
                                break;
                            }
                        }
                        if (!isNoWarehousing) {
                            pickingRestDbDto.setCode("500");
                            pickingRestDbDto.setMessage("该批次中存在已经入库的数据，请核实后输入!");
                            return pickingRestDbDto;
                        }
                        //净重总数
                        BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                        //入库数量总数
                        BigDecimal bigDecimalWarehouseNum = new BigDecimal(0);
                        //循环明细信息
                        for (WipCompletionDetail entity : wipCompletionDetailList) {
                            bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                            bigDecimalWarehouseNum = bigDecimalWarehouseNum.add(new BigDecimal(String.valueOf(entity.getReceiptQuantity())));
                        }

                        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));
                        //获取单位字典值
                        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                        //判断单位
                        if ("2".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是千克
                            if (wipCompletion.getActualQuantity() == null) {
                                wipCompletion.setActualQuantity(bigDecimalNetWeight.toString());
                                wipCompletion.setWarehousingWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                                wipCompletion.setWarehousingNum(Integer.parseInt(bigDecimalWarehouseNum.toString()));
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                String s = bigDecimal.add(bigDecimalNetWeight).toString();
                                wipCompletion.setActualQuantity(s);

                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                String s1 = bigDecimal1.add(bigDecimalNetWeight).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));

                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingNum()));
                                String s2 = bigDecimal2.add(bigDecimalWarehouseNum).toString();
                                wipCompletion.setWarehousingNum(Integer.parseInt(s2));
                            }
                        } else if ("3".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                BigDecimal bigDecimal = new BigDecimal(String.valueOf(bigDecimalNetWeight.toString()));
                                BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                                wipCompletion.setActualQuantity(divide.toString());
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                String s1 = bigDecimal1.add(bigDecimalNetWeight).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));

                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingNum()));
                                String s2 = bigDecimal2.add(bigDecimalWarehouseNum).toString();
                                wipCompletion.setWarehousingNum(Integer.parseInt(s2));
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(bigDecimalNetWeight.toString()));
                                BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                                String s = bigDecimal.add(divide).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal11 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                String s1 = bigDecimal11.add(bigDecimalNetWeight).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));

                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingNum()));
                                String s2 = bigDecimal2.add(bigDecimalWarehouseNum).toString();
                                wipCompletion.setWarehousingNum(Integer.parseInt(s2));
                            }
                        } else {
                            if (wipCompletion.getActualQuantity() == null) {
                                wipCompletion.setActualQuantity(bigDecimalWarehouseNum.toString());
                                wipCompletion.setWarehousingWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                                wipCompletion.setWarehousingNum(Integer.parseInt(bigDecimalWarehouseNum.toString()));
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                String s = bigDecimal.add(bigDecimalWarehouseNum).toString();
                                wipCompletion.setActualQuantity(s);

                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                String s1 = bigDecimal1.add(bigDecimalNetWeight).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));

                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingNum()));
                                String s2 = bigDecimal2.add(bigDecimalWarehouseNum).toString();
                                wipCompletion.setWarehousingNum(Integer.parseInt(s2));
                            }
                        }


                        pickingRestDbDto.setQuantityIdentification(wipCompletion.getPlannedWeight() + "/" + wipCompletion.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + "," + "净重:" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + bigDecimalWarehouseNum + "," + "录入成功");
                        pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                        pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setWarehouseNumber(String.valueOf(bigDecimalWarehouseNum));


                        //修改仓库表中对应的数据状态
                        List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                        List<WmsStockInfo> wmsStockInfoArrayList = new ArrayList<>();

                        Long menuId = feignService.getIdByMenuName("完工入库");
                        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

                        //如果配置了送检,则校验是否配了检验方案
                        if (sysDocument.getDocInspectionMark()==1){

                            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                            if (documentCheckDtoList==null){
                                throw new GlobalException("请先在单据配置中配置送检方案");
                            }


                            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualitySchemeConfigurationVo.setMaterialCode(wipCompletion.getMaterialCode());
                            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                            if (!check){
                                throw new GlobalException("该物料不存在对应的检验方案");

                            }
                        }

                        //修改明细状态
                        for (WipCompletionDetail entity : wipCompletionDetailList) {
                            entity.setStatus(2);
                        }
                        wipCompletionDetailService.updateBatchById(wipCompletionDetailList);
//                        //并且校验是否还有待入库的明细
//                        List<WipCompletionDetail> collect = wipCompletionDetailList.stream().filter(entity -> entity.getStatus() == 1).collect(Collectors.toList());
                        List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                        boolean allTrue = true;
                        for (WipCompletionDetail entity : wipCompletionDetails) {
                            if (entity.getStatus() == 1) {
                                allTrue = false;
                                break;
                            }
                        }
                        //需求量
                        double aDouble = Double.parseDouble(wipCompletion.getActualQuantity());
                        //计划量
                        double plannedWeight = wipCompletion.getPlannedWeight();
                        boolean b = Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(plannedWeight);
                        if (b) {

                            //如果配置了送检
                            if (sysDocument.getDocInspectionMark() == 1) {
                                if (allTrue) {
                                    wipCompletion.setStatus(3);
                                } else {
                                    wipCompletion.setStatus(2);
                                }
                                // 生成品质检验单
                                if (sysDocument.getDocCode() == null) {
                                    throw new GlobalException("未进行单据配置");
                                }
                                List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                                if (documentCheckDtoList.size() < 1) {
                                    throw new GlobalException("未进行检验单生成配置");
                                }
                                //通过物料编码获取物料类别
                                //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
                                //获取明细列表
                                List<WipCompletionDetail> salesReturnDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                                StringBuilder stringBuilder = new StringBuilder();
                                for (WipCompletionDetail entity : salesReturnDetailList) {
                                    stringBuilder.append(entity.getBatchNo()).append(",");
                                }
                                StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                                for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                                    if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                                        QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                                        qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                                        qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                                        qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                                        qualityInspectionDocumentVo.setMaterialCode(wipCompletion.getMaterialCode());
                                        qualityInspectionDocumentVo.setBatchNo(stringBuilder1.toString());
                                        qualityInspectionDocumentVo.setAssociatedNo(wipCompletion.getReceiptNo());
                                        qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                        qualityInspectionDocumentVo.setModeType(15);

                                        List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                                        for (WipCompletionDetail entity : salesReturnDetailList) {
                                            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                            materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                                            materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                                            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                        }
                                        qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);


//                                            qualityFeginService.add(qualityInspectionDocumentVo);
                                        boolean b1 = qualityFeginService.addWares(qualityInspectionDocumentVo);
                                        if (!b1) {
                                            throw new GlobalException("未进行单据配置，请前往品质检验——>检验项目进行配置");
                                        }
//                                        AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
//                                        String code = add.get("code").toString();
//                                        if ("500".equals(code)) {
//                                            PickingRestDbDto pickingRestDbDto1 = new PickingRestDbDto();
//                                            pickingRestDbDto1.setMessage("生成品质检验单失败");
//                                            pickingRestDbDto1.setCode("500");
//                                            return pickingRestDbDto1;
//                                        }
                                    }
                                }

                                //修改仓库数据
                                for (WmsStockInfo entity : wmsStockInfoList) {
                                    entity.setWsiMaterialStatus(2);
                                    entity.setWsiMaterialType(publicGoods.getMaterialType());
                                    entity.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                                    entity.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                                    entity.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                                    entity.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                                    entity.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                                    entity.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                                    entity.setWsiDocNum(wipCompletion.getReceiptNo());
                                    entity.setWsiMaterialGrade("1");
                                    entity.setCreateUser(SecurityUtils.getUsername());
                                    entity.setCreateTime(new Date());
                                    entity.setWsiReveiveTime(new Date());
                                    wmsStockInfoArrayList.add(entity);
                                }
                                wmsStockInfoService.updateBatchById(wmsStockInfoArrayList);
//                                //修改明细状态
//                                for (WipCompletionDetail entity : wipCompletionDetailList) {
//                                    entity.setStatus(2);
//                                }
//                                wipCompletionDetailService.updateBatchById(wipCompletionDetailList);
//                                //如果该单据明细中都已经待检验，就把单据修改为待检验
//                                List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
//                                List<WipCompletionDetail> collect1 = wipCompletionDetails.stream().filter(entity -> entity.getStatus() != 2).collect(Collectors.toList());
//                                if (collect1.size() == 0) {
//                                    wipCompletion.setStatus(3);
//                                }
                                wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                updateById(wipCompletion);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            } else {
                                if (allTrue) {
                                    wipCompletion.setStatus(4);
                                } else {
                                    wipCompletion.setStatus(2);
                                }
                                wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                updateById(wipCompletion);

                                //修改仓库数据
                                for (WmsStockInfo entity : wmsStockInfoList) {
                                    entity.setWsiMaterialStatus(2);
                                    entity.setWsiMaterialType(publicGoods.getMaterialType());
                                    entity.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                                    entity.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                                    entity.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                                    entity.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                                    entity.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                                    entity.setWsiDocNum(wipCompletion.getReceiptNo());
                                    entity.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                                    entity.setWsiReveiveTime(new Date());
                                    entity.setWsiMaterialGrade("1");
                                    entity.setCreateUser(SecurityUtils.getUsername());
                                    entity.setCreateTime(new Date());
                                    wmsStockInfoArrayList.add(entity);
                                }
                                wmsStockInfoService.updateBatchById(wmsStockInfoArrayList);
//                                //修改明细状态
//                                for (WipCompletionDetail entity : wipCompletionDetailList) {
//                                    entity.setStatus(2);
//                                }
//                                wipCompletionDetailService.updateBatchById(wipCompletionDetailList);
//                                //如果该单据明细中都已经待检验，就把单据修改为待检验
//                                List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getBatchNo, pickingRestDbVo.getInputValue()).eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
//                                List<WipCompletionDetail> collect1 = wipCompletionDetails.stream().filter(entity -> entity.getStatus() != 2).collect(Collectors.toList());
//                                if (collect1.size() == 0) {
//                                    wipCompletion.setStatus(3);
//                                }
                                wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                updateById(wipCompletion);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                        }
                        //修改明细状态
//                        for (WipCompletionDetail entity : wipCompletionDetailList) {
//                            entity.setStatus(2);
                        //修改仓库数据
                        for (WmsStockInfo wmsStockInfo : wmsStockInfoList) {
                            wmsStockInfo.setWsiMaterialStatus(2);
                            wmsStockInfo.setWsiMaterialType(publicGoods.getMaterialType());
                            wmsStockInfo.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                            wmsStockInfo.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                            wmsStockInfo.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                            wmsStockInfo.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                            wmsStockInfo.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                            wmsStockInfo.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                            wmsStockInfo.setWsiDocNum(wipCompletion.getReceiptNo());
                            wmsStockInfo.setWsiMaterialGrade("1");
                            wmsStockInfo.setWsiReveiveTime(new Date());
                            wmsStockInfo.setCreateUser(SecurityUtils.getUsername());
                            wmsStockInfo.setCreateTime(new Date());
                            wmsStockInfoArrayList.add(wmsStockInfo);
                        }
                        wmsStockInfoService.updateBatchById(wmsStockInfoArrayList);
//                        }
//                        wipCompletionDetailService.updateBatchById(wipCompletionDetailList);
                        wipCompletion.setStatus(2);
                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                        updateById(wipCompletion);
                        pickingRestDbDto.setCode("200");
                        return pickingRestDbDto;
                    }
                }


                //库位撤销
                if ("3".equals(pickingRestDbVo.getType())) {
//                    //如果是第一步，需要查询库位信息
//                    if (pickingRestDbVo.getExecutionOrder() == 1) {
//                        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
//                        if (warehouseCode.getCombinationName() == null) {
//                            pickingRestDbDto.setMessage("该仓库不存在，请核实");
//                            pickingRestDbDto.setCode("500");
//                            return pickingRestDbDto;
//                        }
//                        pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
//                        pickingRestDbDto.setCkId(warehouseCode.getCkId());
//                        pickingRestDbDto.setKqId(warehouseCode.getKqId());
//                        pickingRestDbDto.setKwId(warehouseCode.getKwId());
//                        pickingRestDbDto.setMessage("操作成功");
//                        pickingRestDbDto.setCode("200");
//                        return pickingRestDbDto;
//                    }
                    //如果是第二步，需要根据批次号查询明细信息
//                    if (pickingRestDbVo.getExecutionOrder() == 2) {
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()).eq(WmsStockInfo::getWsiMaterialStatus, 2));
                    if (wmsStockInfo == null) {
                        pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    wmsStockInfo.setWsiMaterialStatus(1);
                    wmsStockInfo.setWsiWarehourse("");
                    wmsStockInfo.setWsiReservoirArea("");
                    wmsStockInfo.setWsiStorageLoaction("");
                    wmsStockInfo.setWsiWarehourseInfo("");
                    wmsStockInfoMapper.updateById(wmsStockInfo);

                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));
                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                    //同时修改采购入库明细状态
                    WipCompletionDetail wipCompletionDetail = wipCompletionDetailMapper.selectOne(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));

                    wipCompletionDetail.setStatus(1);
                    wipCompletionDetailService.updateById(wipCompletionDetail);

                    //完工入库单数量和重量扣减
                    wipCompletion.setWarehousingNum(wipCompletion.getWarehousingNum() - 1);
                    BigDecimal subtract = new BigDecimal(wipCompletion.getActualQuantity()).subtract(new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight())));
                    wipCompletion.setWarehousingWeight(Double.parseDouble(subtract.toString()));
                    wipCompletion.setActualQuantity(subtract.toString());


                    //判断条数修改采购入库状态
                    List<WipCompletionDetail> list = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, pickingRestDbVo.getId()));
                    boolean isSuccess = true;
                    for (WipCompletionDetail entity : list) {
                        if (entity.getStatus() == 2 || entity.getStatus() == 3) {
                            isSuccess = false;
                            break;
                        }
                    }
                    //假如全是待入库就修改完工入库为待入库
                    if (isSuccess) {
                        wipCompletion.setStatus(1);
                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());

                    }
                    updateById(wipCompletion);

                    //设置返回信息
                    pickingRestDbDto.setMessage("物料号码:" + wipCompletionDetail.getMaterialNumber() + "," + "净重:" + wipCompletionDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + wipCompletionDetail.getReceiptQuantity() + "," + "撤销成功");
                    pickingRestDbDto.setQuantityIdentification(wipCompletion.getPlannedWeight() + "/" + wipCompletion.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(wipCompletion.getWarehousingNum()));
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
//                    }
                }
            } else {
                pickingRestDbDto.setCode("500");
                pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
                return pickingRestDbDto;
            }
            return pickingRestDbDto;
        } else {
            pickingRestDbDto.setMessage("只能操作自动生成的数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
    }

    /**
     * 完工入库pda(手动生成)
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto manualWipCompletionPda(PickingRestDbVo pickingRestDbVo) throws Exception {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        WipCompletion wipCompletion = getById(pickingRestDbVo.getId());
        //校验生成方式
        if (wipCompletion.getGenerationMethod() == 2) {
            //待入库和入库中的数据才能进行操作
            if (wipCompletion.getStatus() == 1 || wipCompletion.getStatus() == 2) {
                //扫码入库
                if ("1".equals(pickingRestDbVo.getType())) {
                    //如果是第一步，需要查询库位信息
                    if (pickingRestDbVo.getExecutionOrder() == 1) {
                        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                        if (warehouseCode.getCombinationName() == null) {
                            pickingRestDbDto.setMessage("该仓库不存在，请核实");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }
                        pickingRestDbDto.setCombinationName(warehouseCode.getCombinationName());
                        pickingRestDbDto.setCkId(warehouseCode.getCkId());
                        pickingRestDbDto.setKqId(warehouseCode.getKqId());
                        pickingRestDbDto.setKwId(warehouseCode.getKwId());
                        pickingRestDbDto.setMessage("操作成功");
                        pickingRestDbDto.setCode("200");
                        return pickingRestDbDto;
                    }
                    //如果是第二步，需要根据物料号码保存明细信息
                    if (pickingRestDbVo.getExecutionOrder() == 2) {
                        WipCompletionVo wipCompletionVo = new WipCompletionVo();
                        //获取完工入库列表
                        WipCompletion byId = getById(pickingRestDbVo.getId());
                        List<WipCompletionDto> wipCompletionList = wipCompletionMapper.getWipCompletionList(wipCompletionVo);
                        //获取明细对象
//                        WipCompletionDetail wipCompletionDetailObject = pickingRestDbVo.getWipCompletionDetailObject();


                        String materialNumber = pickingRestDbVo.getInputValue();
                        //查水刺产出的产品号码获取数据
                        AjaxResult spunlaceDetail = feignProductionService.getSpunlaceDetail(materialNumber);
                        SpunlaceOutputDetailDto data = JSON.parseObject(JSON.toJSONString(spunlaceDetail.get("data")), SpunlaceOutputDetailDto.class);
                        //成品称重页面的上表产品号码获取数据
                        AjaxResult weighingFinishedData = feignProductionService.getFinishedData(materialNumber);
                        WeighingFinishedMaterialProductDto data1 = JSON.parseObject(JSON.toJSONString(weighingFinishedData.get("data")), WeighingFinishedMaterialProductDto.class);
                        if (data.getMaterialCode() == null && data1.getMaterialCode() == null) {
                            pickingRestDbDto.setMessage("没有查询到对应物料，请核实后输入!");
                            pickingRestDbDto.setCode("500");
                            return pickingRestDbDto;
                        }

                        Long menuId = feignService.getIdByMenuName("完工入库");
                        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

                        //如果配置了送检,则校验是否配了检验方案
                        if (sysDocument.getDocInspectionMark()==1){

                            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                            if (documentCheckDtoList==null){
                                throw new GlobalException("请先在单据配置中配置送检方案");
                            }

                            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));

                            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualitySchemeConfigurationVo.setMaterialCode(wipCompletion.getMaterialCode());
                            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                            if (!check){
                                throw new GlobalException("该物料不存在对应的检验方案");

                            }
                        }

                        //如果配置了送检,则校验是否配了检验方案
                        if (sysDocument.getDocInspectionMark()==1){

                            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                            if (documentCheckDtoList==null){
                                throw new GlobalException("请先在单据配置中配置送检方案");
                            }

                            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));

                            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                            qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                            qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                            qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                            qualitySchemeConfigurationVo.setMaterialCode(wipCompletion.getMaterialCode());
                            boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                            if (!check){
                                throw new GlobalException("该物料不存在对应的检验方案");

                            }
                        }

                        WipCompletionDetail wipCompletionDetail = new WipCompletionDetail();
                        if (data.getMaterialCode() != null) {
                            //根据扫描的物料编码和入库列表数据进行比对
//                            for (WipCompletionDto entity : wipCompletionList) {
                            //如果对应的编码相等，就将该明细存入
                            if (byId.getMaterialCode().equals(data.getMaterialCode())) {
                                //是否配置了送检
                                if (sysDocument.getDocInspectionMark() == 1) {
                                    //修改明细状态为待送检
                                    wipCompletionDetail.setStatus(1);
                                } else if (sysDocument.getDocHandoverMark() == 1) {
                                    //修改明细状态为待交接
                                    wipCompletionDetail.setStatus(2);
                                } else {
                                    wipCompletionDetail.setStatus(3);
                                }
                                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, data.getMaterialCode()));

                                wipCompletionDetail.setMaterialCode(data.getMaterialCode());
                                wipCompletionDetail.setMaterialNumber(pickingRestDbVo.getInputValue());
                                wipCompletionDetail.setGrossWeight(data.getGrossWeight());
                                wipCompletionDetail.setNetWeight(data.getNetWeight());
                                wipCompletionDetail.setReceiptQuantity(1);
                                wipCompletionDetail.setBatchNo(data.getProductionBatch());
                                wipCompletionDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                                wipCompletionDetail.setWarehouseInBy(SecurityUtils.getUsername());
                                wipCompletionDetail.setWarehouseInTime(new Date());
                                wipCompletionDetail.setWipCompletionId(byId.getId());
                                wipCompletionDetailService.save(wipCompletionDetail);

                                //查询该物料是否入库过
                                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wipCompletionDetail.getMaterialNumber()));

                                if (wmsStockInfo != null) {
                                    pickingRestDbDto.setMessage("该数据已经入库");
                                    pickingRestDbDto.setCode("500");
                                    return pickingRestDbDto;
                                }

                                //向仓库表中添加对应的数据
                                WmsStockInfo wmsStockInfo1 = new WmsStockInfo();
                                wmsStockInfo1.setWsiMaterialNumber(wipCompletionDetail.getMaterialNumber())
                                        .setWsiMaterialCode(wipCompletionDetail.getMaterialCode())
                                        .setWsiMaterialNum(1)
                                        .setWsiMaterialStatus(2)
                                        .setWsiMaterialType(publicGoods.getMaterialType())
                                        .setWsiMaterialBatch(wipCompletionDetail.getBatchNo())
                                        .setWsiGorssWeight(wipCompletionDetail.getGrossWeight())
                                        .setWsiNetWeight(wipCompletionDetail.getNetWeight())
                                        .setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()))
                                        .setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()))
                                        .setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()))
                                        .setWsiWarehourseInfo(pickingRestDbVo.getCombinationName())
                                        .setWsiReveiveTime(new Date())
                                        .setCreateUser(SecurityUtils.getUsername())
                                        .setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()))
                                        .setWsiDocNum(wipCompletion.getReceiptNo())
                                        .setWsiConnectNum(wipCompletion.getMakingOrderNo())
                                        .setWsiMaterialGrade("1")
                                        .setCreateTime(new Date());
                                wmsStockInfoService.save(wmsStockInfo1);
                            } else {
                                throw new GlobalException("选取的物料和单据不一致");
                            }
//                            }
                        } else {
                            //根据扫描的物料编码和入库列表数据进行比对
//                            for (WipCompletionDto entity : wipCompletionList) {
                            //如果对应的编码相等，就将该明细存入
                            if (byId.getMaterialCode().equals(data1.getMaterialCode())) {
                                //是否配置了送检
                                if (sysDocument.getDocInspectionMark() == 1) {
                                    //修改明细状态为待送检
                                    wipCompletionDetail.setStatus(1);
                                } else if (sysDocument.getDocHandoverMark() == 1) {
                                    //修改明细状态为待交接
                                    wipCompletionDetail.setStatus(2);
                                } else {
                                    wipCompletionDetail.setStatus(3);
                                }
                                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, data1.getMaterialCode()));

                                wipCompletionDetail.setMaterialCode(data1.getMaterialCode());
                                wipCompletionDetail.setMaterialNumber(pickingRestDbVo.getInputValue());
                                wipCompletionDetail.setGrossWeight(Double.parseDouble(data1.getGrossWeight()));
                                wipCompletionDetail.setNetWeight(Double.parseDouble(data1.getNetWeight()));
                                wipCompletionDetail.setReceiptQuantity(1);
                                wipCompletionDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                                wipCompletionDetail.setWarehouseInBy(SecurityUtils.getUsername());
                                wipCompletionDetail.setWarehouseInTime(new Date());
                                wipCompletionDetail.setWipCompletionId(byId.getId());
                                wipCompletionDetailService.save(wipCompletionDetail);

                                //查询该物料是否入库过
                                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, wipCompletionDetail.getMaterialNumber()).eq(WmsStockInfo::getWsiMaterialStatus, 2));

                                if (wmsStockInfo != null) {
                                    pickingRestDbDto.setMessage("该数据已经入库");
                                    pickingRestDbDto.setCode("500");
                                    return pickingRestDbDto;
                                }

                                //向仓库表中添加对应的数据
                                WmsStockInfo wmsStockInfo1 = new WmsStockInfo();
                                wmsStockInfo1.setWsiMaterialNumber(wipCompletionDetail.getMaterialNumber())
                                        .setWsiMaterialCode(wipCompletionDetail.getMaterialCode())
                                        .setWsiMaterialNum(1)
                                        .setWsiMaterialStatus(2)
                                        .setWsiMaterialBatch(wipCompletionDetail.getBatchNo())
                                        .setWsiGorssWeight(wipCompletionDetail.getGrossWeight())
                                        .setWsiNetWeight(wipCompletionDetail.getNetWeight())
                                        .setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()))
                                        .setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()))
                                        .setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()))
                                        .setWsiWarehourseInfo(pickingRestDbVo.getCombinationName())
                                        .setWsiReveiveTime(new Date())
                                        .setCreateUser(SecurityUtils.getUsername())
                                        .setWsiMaterialType(publicGoods.getMaterialType())
                                        .setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()))
                                        .setWsiDocNum(wipCompletion.getReceiptNo())
                                        .setWsiConnectNum(wipCompletion.getMakingOrderNo())
                                        .setWsiMaterialGrade("1")
                                        .setCreateTime(new Date());
                                wmsStockInfoService.save(wmsStockInfo1);
                            } else {
                                throw new GlobalException("选取的物料和单据不一致");
                            }
                        }
//                        }
//                        if (wipCompletionDetail.getMaterialCode() == null) {
//                            pickingRestDbDto.setMessage("没有匹配的物料，请核实!");
//                            pickingRestDbDto.setCode("500");
//                            return pickingRestDbDto;
//                        }
                        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletionDetail.getMaterialCode()));
                        //获取单位字典值
                        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

                        //判断单位
                        if ("2".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是千克
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                wipCompletion.setActualQuantity(String.valueOf(wipCompletionDetail.getNetWeight()));
                                //修改采购入库信息入库重量
                                wipCompletion.setWarehousingWeight(wipCompletionDetail.getNetWeight());
                                wipCompletion.setWarehousingNum(Integer.parseInt(String.valueOf(wipCompletionDetail.getReceiptQuantity())));
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s = bigDecimal.add(bigDecimal1).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                                BigDecimal bigDecimal4 = new BigDecimal(wipCompletion.getWarehousingNum());
                                BigDecimal bigDecimal5 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                int i = Integer.parseInt(bigDecimal4.add(bigDecimal5).toString());
                                wipCompletion.setWarehousingNum(i);
                            }
                        } else if ("3".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                BigDecimal bigDecimal = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                                wipCompletion.setActualQuantity(divide.toString());
                                //修改采购入库信息入库重量
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                                BigDecimal bigDecimal4 = new BigDecimal(wipCompletion.getWarehousingNum());
                                BigDecimal bigDecimal5 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                int i = Integer.parseInt(bigDecimal4.add(bigDecimal5).toString());
                                wipCompletion.setWarehousingNum(i);
                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                                String s = bigDecimal.add(divide).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                                BigDecimal bigDecimal4 = new BigDecimal(wipCompletion.getWarehousingNum());
                                BigDecimal bigDecimal5 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                int i = Integer.parseInt(bigDecimal4.add(bigDecimal5).toString());
                                wipCompletion.setWarehousingNum(i);
                            }
                        } else {
                            if (wipCompletion.getActualQuantity() == null || "".equals(wipCompletion.getActualQuantity())) {
                                wipCompletion.setActualQuantity(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                //修改采购入库信息入库重量
                                wipCompletion.setWarehousingWeight(wipCompletionDetail.getNetWeight());
                                wipCompletion.setWarehousingNum(Integer.parseInt(String.valueOf(wipCompletionDetail.getReceiptQuantity())));

                            } else {
                                BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                                BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                String s = bigDecimal.add(bigDecimal1).toString();
                                wipCompletion.setActualQuantity(s);
                                //修改采购入库信息入库重量
                                BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                                BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                                String s1 = bigDecimal2.add(bigDecimal3).toString();
                                wipCompletion.setWarehousingWeight(Double.parseDouble(s1));

                                BigDecimal bigDecimal4 = new BigDecimal(wipCompletion.getWarehousingNum());
                                BigDecimal bigDecimal5 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                                int i = Integer.parseInt(bigDecimal4.add(bigDecimal5).toString());
                                wipCompletion.setWarehousingNum(i);
                            }
                        }

                        pickingRestDbDto.setQuantityIdentification(wipCompletion.getPlannedWeight() + "/" + wipCompletion.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setMessage("物料号码:" + wipCompletionDetail.getMaterialNumber() + "," + "净重:" + wipCompletionDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + wipCompletionDetail.getReceiptQuantity() + "," + "录入成功");
                        pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                        pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                        pickingRestDbDto.setWarehouseNumber(String.valueOf(wipCompletion.getWarehousingNum()));


                        double aDouble = Double.parseDouble(wipCompletion.getActualQuantity());
                        double planWeight = wipCompletion.getPlannedWeight();

                        //判断是否配置了超收
                        if (sysDocument.getDocExcessMark() == 2 && publicGoods.getMaterialClosed() == 2) {
                            if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(planWeight)) {
                                //如果配置了送检
                                if (sysDocument.getDocInspectionMark() == 1) {
                                    wipCompletion.setStatus(3);
                                    // 生成品质检验单
                                    if (sysDocument.getDocCode() == null) {
                                        throw new GlobalException("未进行单据配置");
                                    }
                                    List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                                    if (documentCheckDtoList.size() < 1) {
                                        throw new GlobalException("未进行检验单生成配置");
                                    }
                                    //通过物料编码获取物料类别
                                    //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
                                    //获取明细列表
                                    List<WipCompletionDetail> salesReturnDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
                                    StringBuilder stringBuilder = new StringBuilder();
                                    for (WipCompletionDetail entity : salesReturnDetailList) {
                                        stringBuilder.append(entity.getBatchNo()).append(",");
                                    }
                                    StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                                    for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                                        if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                                            qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                                            qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                                            qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                                            qualityInspectionDocumentVo.setMaterialCode(wipCompletion.getMaterialCode());
                                            qualityInspectionDocumentVo.setBatchNo(stringBuilder1.toString());
                                            qualityInspectionDocumentVo.setAssociatedNo(wipCompletion.getReceiptNo());
                                            qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
//                                            qualityInspectionDocumentVo.setDifferentString(customerManagement.getCustomerNum());
                                            qualityInspectionDocumentVo.setModeType(15);

                                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                                            for (WipCompletionDetail entity : salesReturnDetailList) {
                                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                                materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                                                materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                                                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                            }
                                            qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

//                                            AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
//                                            String code = add.get("code").toString();
                                            boolean b = qualityFeginService.addWares(qualityInspectionDocumentVo);
                                            if (!b) {
                                                PickingRestDbDto pickingRestDbDto1 = new PickingRestDbDto();
                                                pickingRestDbDto1.setMessage("生成品质检验单失败");
                                                pickingRestDbDto1.setCode("500");
                                                return pickingRestDbDto1;
                                            }
                                        }
                                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                        updateById(wipCompletion);
                                        pickingRestDbDto.setCode("200");
                                        return pickingRestDbDto;
                                    }
                                    //如果配置了交接
                                    if (sysDocument.getDocInspectionMark() == 1) {
                                        wipCompletion.setStatus(3);
                                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                        updateById(wipCompletion);
                                        pickingRestDbDto.setCode("200");
                                        return pickingRestDbDto;
                                    } else {
                                        wipCompletion.setStatus(4);
                                        wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                                        updateById(wipCompletion);
                                        pickingRestDbDto.setCode("200");
                                        return pickingRestDbDto;
                                    }
                                }
                            }
                            pickingRestDbDto.setCode("200");
                            wipCompletion.setStatus(2);
                            wipCompletion.setWarehousingWarehouse(pickingRestDbVo.getKwId());
                            updateById(wipCompletion);
                            return pickingRestDbDto;
                        }
                    }
                }
                //条码撤销
                if ("2".equals(pickingRestDbVo.getType())) {
                    //如果是第一步，需要查询库位信息
//                    if (pickingRestDbVo.getExecutionOrder() == 1) {
//                        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
//                        if (warehouseCode.getCombinationName() == null) {
//                            pickingRestDbDto.setMessage("该仓库不存在，请核实");
//                            pickingRestDbDto.setCode("500");
//                            return pickingRestDbDto;
//                        }
//                        pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
//                        pickingRestDbDto.setCkId(warehouseCode.getCkId());
//                        pickingRestDbDto.setKqId(warehouseCode.getKqId());
//                        pickingRestDbDto.setKwId(warehouseCode.getKwId());
//                        pickingRestDbDto.setMessage("操作成功");
//                        pickingRestDbDto.setCode("200");
//                        return pickingRestDbDto;
//                    }
                    //如果是第二步，需要根据物料号码查询明细信息
//                    if (pickingRestDbVo.getExecutionOrder() == 2) {
                    //查询该条码是否扫描过
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));
                    if (wmsStockInfo == null) {
                        pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    wmsStockInfoMapper.deleteById(wmsStockInfo);

                    //同时删除采购入库明细状态
                    WipCompletionDetail wipCompletionDetail = wipCompletionDetailMapper.selectOne(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));

                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));
                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                    //设置返回信息
                    pickingRestDbDto.setMessage("物料号码:" + wipCompletionDetail.getMaterialNumber() + "," + "净重:" + wipCompletionDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + wipCompletionDetail.getReceiptQuantity() + "," + "撤销成功");
                    pickingRestDbDto.setQuantityIdentification(wipCompletion.getPlannedWeight() + "/" + wipCompletion.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(wipCompletion.getWarehousingNum()));

                    List<WipCompletionDetail> list = wipCompletionDetailService.list();
                    //判断条数修改采购入库状态
                    if (list.size() == 0) {
                        wipCompletion.setWarehousingWeight(0);
                        wipCompletion.setWarehousingNum(0);
                        wipCompletion.setActualQuantity("0");
                        wipCompletion.setStatus(1);
                    } else {
                        wipCompletion.setWarehousingNum(wipCompletion.getWarehousingNum() - 1);
                        //判断单位
                        BigDecimal bigDecimal = new BigDecimal(wipCompletion.getActualQuantity());
                        BigDecimal bigDecimal1;
                        if ("2".equals(publicGoods.getMaterialUnit())) {
                            //如果是千克
                            bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                            String s = bigDecimal.subtract(bigDecimal1).toString();
                            wipCompletion.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                            String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                            wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                            //入库数量
                        } else if ("3".equals(publicGoods.getMaterialUnit())) {
                            //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                            BigDecimal bigDecimalNetWeight = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                            BigDecimal divide = bigDecimalNetWeight.divide(new BigDecimal("1000"));
                            String s = bigDecimal.subtract(divide).toString();
                            wipCompletion.setActualQuantity(s);
                            //修改完工入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                            String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                            wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                        } else {
                            //不是千克
                            bigDecimal1 = new BigDecimal(String.valueOf(wipCompletionDetail.getReceiptQuantity()));
                            String s = bigDecimal.subtract(bigDecimal1).toString();
                            wipCompletion.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(wipCompletion.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(wipCompletionDetail.getNetWeight()));
                            String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                            wipCompletion.setWarehousingWeight(Double.parseDouble(s1));
                        }
                        //入库数量
                        wipCompletion.setWarehousingNum(wipCompletion.getWarehousingNum() - 1);
                    }

                    wipCompletionDetailMapper.deleteById(wipCompletionDetail);
                    updateById(wipCompletion);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
//                    }
                }
            } else {
                pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
                pickingRestDbDto.setCode("500");
                return pickingRestDbDto;
            }
            return pickingRestDbDto;
        } else {
            pickingRestDbDto.setMessage("步骤不正确,请核实!");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
    }


    /**
     * 完工入库拣货撤销
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCancellation(PickingRestDbVo pickingRestDbVo) {
        //根据其它入库id获取明细数据
        List<WipCompletionDetail> wipCompletionDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, pickingRestDbVo.getId()));
        //根据批次号查询仓库信息
        List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, wipCompletionDetailList.get(0).getBatchNo()));
        //删除仓储数据
        wmsStockInfoMapper.deleteBatchIds(wmsStockInfoList);
        //删除明细数据
        wipCompletionDetailMapper.deleteBatchIds(wipCompletionDetailList);
        //修改销售退货状态
        WipCompletion wipCompletion = getById(pickingRestDbVo.getId());
        wipCompletion.setStatus(1);
        wipCompletion.setWarehousingNum(0);
        wipCompletion.setWarehousingWeight(0);
        wipCompletion.setActualQuantity("0");
        //删除关联的检验单
        String relevanceDoc = wipCompletion.getReceiptNo();
        qualityFeginService.removeDoc(relevanceDoc);
        return updateById(wipCompletion);
    }


    /**
     * 完工入库拣货完成
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCompleted(PickingRestDbVo pickingRestDbVo) throws Exception {
        WipCompletion wipCompletion = getById(pickingRestDbVo.getId());
        //需求量
        double aDouble = Double.parseDouble(wipCompletion.getActualQuantity());
        //退货量
        double planWeight = wipCompletion.getPlannedWeight();
        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, wipCompletion.getMaterialCode()));

        Long menuId = feignService.getIdByMenuName("完工入库");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //配置了超收
//        if (sysDocument.getDocExcessMark() == 1) {
//            if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(planWeight)) {
        //如果配置了送检
        if (sysDocument.getDocInspectionMark() == 1) {
            wipCompletion.setStatus(3);
            // 生成品质检验单
            if (sysDocument.getDocCode() == null) {
                throw new GlobalException("未进行单据配置");
            }
            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList.size() < 1) {
                throw new GlobalException("未进行检验单生成配置");
            }
            //通过物料编码获取物料类别
            //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
            //获取明细列表
            List<WipCompletionDetail> salesReturnDetailList = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
            StringBuilder stringBuilder = new StringBuilder();
            for (WipCompletionDetail entity : salesReturnDetailList) {
                stringBuilder.append(entity.getBatchNo()).append(",");
            }
            StringBuilder stringBuilderBatch = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                    QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                    qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                    qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                    qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                    qualityInspectionDocumentVo.setMaterialCode(wipCompletion.getMaterialCode());
                    qualityInspectionDocumentVo.setBatchNo(stringBuilderBatch.toString());
                    qualityInspectionDocumentVo.setAssociatedNo(wipCompletion.getReceiptNo());
                    qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
//                    qualityInspectionDocumentVo.setDifferentString(customerManagement.getCustomerNum());
                    qualityInspectionDocumentVo.setModeType(15);

                    List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                    for (WipCompletionDetail entity : salesReturnDetailList) {
                        MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                        materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                        materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                        materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                    }
                    qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                    AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
                    String code = add.get("code").toString();
                    if ("500".equals(code)) {
                        throw new GlobalException("生成品质检验单失败");
                    }
                }
            }
            return updateById(wipCompletion);
        }
        //如果配置了交接
        if (sysDocument.getDocHandoverMark() == 1) {
            wipCompletion.setStatus(4);
            return updateById(wipCompletion);
        }
//            }
//        }
        wipCompletion.setStatus(5);
        return updateById(wipCompletion);
    }

    /**
     * 新增完工入库（其他模块调用）
     *
     * @param wipOtherAddVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean wipOtherAdd(WipOtherAddVo wipOtherAddVo) throws Exception {

        //根据制令单号获取自动生成数据
        WipCompletionDto autoGenerationData = wipCompletionMapper.getAutoGenerationData(wipOtherAddVo);
        if(autoGenerationData==null || "4".equals(autoGenerationData.getStatus()) || "5".equals(autoGenerationData.getStatus())){

            //新增完工入库单
            WipCompletion wipCompletion1 = new WipCompletion();
            String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:finished:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            wipCompletion1.setReceiptNo(authorityCoding)
                    .setDeptId(SecurityUtils.getDeptId())
                    .setStatus(1)
                    .setMakingOrderNo(wipOtherAddVo.getMakingOrderNo())
                    .setMaterialCode(wipOtherAddVo.getMaterialCode())
                    .setMaterialCategory(wipOtherAddVo.getMaterialCategory())
                    .setPlannedWeight(wipOtherAddVo.getPlannedWeight())
                    .setWarehousTime(wipOtherAddVo.getWarehousTime())
                    .setDrawerBy(SecurityUtils.getUsername())
                    .setDrawerTime(new Date())
                    .setReceiveType(wipOtherAddVo.getReceiveType())
                    .setDocumentType(DocumentTypeEnum.WIP_COMPLETION.getCode());

            if (wipOtherAddVo.getGenerationMethod() != 2) {
                wipCompletion1.setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode());
            } else {
                wipCompletion1.setGenerationMethod(GenerationMethodEnum.AUTO_GENERATE.getCode());
            }
            boolean a = save(wipCompletion1);
            if (a) {
                //保存完工入库明细数据
                WipCompletionDetail wipCompletionDetail = new WipCompletionDetail();
                wipCompletionDetail.setMaterialCode(wipOtherAddVo.getMaterialCode())
                        .setMaterialNumber(wipOtherAddVo.getMaterialNumber())
                        .setStatus(1)
                        .setGrossWeight(wipOtherAddVo.getGrossWeight())
                        .setNetWeight(wipOtherAddVo.getNetWeight())
                        .setReceiptQuantity(1)
                        .setBatchNo(wipOtherAddVo.getBatchNo())
                        .setWipCompletionId(wipCompletion1.getId());
                wipCompletionDetailService.save(wipCompletionDetail);
            }
            return a;
        }else {
            //将成品称重数据进行保存到明细
            WipCompletionDetail wipCompletionDetail = new WipCompletionDetail();
            wipCompletionDetail.setMaterialCode(wipOtherAddVo.getMaterialCode())
                    .setMaterialNumber(wipOtherAddVo.getMaterialNumber())
                    .setStatus(1)
                    .setGrossWeight(wipOtherAddVo.getGrossWeight())
                    .setNetWeight(wipOtherAddVo.getNetWeight())
                    .setReceiptQuantity(1)
                    .setBatchNo(wipOtherAddVo.getBatchNo())
                    .setWipCompletionId(autoGenerationData.getId());
            return wipCompletionDetailService.save(wipCompletionDetail);
        }
    }

    /**
     * 完工入库品质回传状态(fegin调用)
     *
     * @param updateStatusByQualityVo
     * @return
     */
    @Override
    public boolean updateStatusByQuality(UpdateStatusByQualityVo updateStatusByQualityVo) {
//        Long menuId = feignService.getIdByMenuName("完工入库");
//        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
//        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //获取完工入库及对应明细信息
        WipCompletion wipCompletion = wipCompletionMapper.selectOne(new QueryWrapper<WipCompletion>().lambda().eq(WipCompletion::getReceiptNo, updateStatusByQualityVo.getAssociatedNo()));

        List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
        //如果单据状态为待检验
        if (wipCompletion.getStatus() == 3) {
            wipCompletion.setStatus(4);
            for (WipCompletionDetail entity : wipCompletionDetails) {
                entity.setStatus(3);
            }
        }
        if (wipCompletionDetails.size() > 0) {
            wipCompletionDetailService.updateBatchById(wipCompletionDetails);
        }

        return updateById(wipCompletion);
    }

    /**
     * 完工入库品质回传状态(品质处理fegin调用)
     *
     * @param returnStatusVo
     * @return
     */
    @Override
    public boolean wipCompletionQualityStatus(ReturnStatusVo returnStatusVo) {
        String associatedNo = returnStatusVo.getAssociatedNo();
        WipCompletion wipCompletion = wipCompletionMapper.selectOne(new QueryWrapper<WipCompletion>().lambda().eq(WipCompletion::getReceiptNo, associatedNo));
        wipCompletion.setStatus(4);
        updateById(wipCompletion);
        List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>().lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));

        List<String> materialNumberList = new ArrayList<>();
        for (WipCompletionDetail entity : wipCompletionDetails) {
            materialNumberList.add(entity.getMaterialNumber());
            entity.setStatus(3);
        }

        wipCompletionDetailService.updateBatchById(wipCompletionDetails);

        //修改对应仓库中物料的等级和状态
        List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
        for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
            wmsStockInfo.setWsiMaterialGrade(String.valueOf(returnStatusVo.getJudgmentGrade()));
            wmsStockInfo.setWsiMaterialStatus(2);
        }


        return wmsStockInfoService.updateBatchById(wmsStockInfos);
    }
}
